package test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

import defaultPackage.JavaSound;

public class Recorder {

	File file;
	String fileName = "untitled";
    AudioInputStream audioInputStream;
    TargetDataLine line;
    protected boolean running;
    ByteArrayOutputStream out;
    AudioFileFormat.Type fileType;
	
	public void run(){
		
		file = null;
        //capture.start();
        fileName = "untitled";
        float sampleRate = 8000;
        int sampleSizeInBits = 8;
        int channels = 1;
        boolean signed = true;
        boolean bigEndian = true;
        Thread captureThread;
        
        
        final AudioFormat format =  new AudioFormat(sampleRate, 
          sampleSizeInBits, channels, signed, bigEndian);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, 
            format);
        
        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line matching " + info + " not supported.");
        }
        else{        
		        try {
		            line = (TargetDataLine) AudioSystem.getLine(info);
		         
		            line.open(format);
		            line.start();
		            
		        	System.out.println("Configurazione finita");
		            Runnable runner = new Runnable() {
		                int bufferSize = (int)format.getSampleRate() * format.getFrameSize();
		                byte buffer[] = new byte[bufferSize];
		         
		                public void run() {
		                  out = new ByteArrayOutputStream();
		                  running = true;
		              		System.out.println("Registrando...");
		                  try {
		                    while (running) {
		                      int count = 
		                        line.read(buffer, 0, buffer.length);
		                      if (count > 0) {
		                        out.write(buffer, 0, count);
		                      }
		                    }
		                    out.close();
		                  } catch (IOException e) {
		                    System.err.println("I/O problems: " + e);
		                    System.exit(-1);
		                  }
		                }
		              };
		              captureThread = new Thread(runner);
		              captureThread.start();
		              

		        } catch (LineUnavailableException ex) { 
		        	System.out.println("Line unavabile");
		        	return;
		        } catch (SecurityException ex) { 
		        	System.out.println("Errore sicurezza");
		            return;
		        } catch (Exception ex) { 
		            System.out.println(ex.getLocalizedMessage());
		            return;
		        }
	              
		        BufferedReader br = new BufferedReader(
                        new InputStreamReader(System.in));
		        
		        try {
					br.readLine();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

		        
		        byte[] bytes = out.toByteArray();
	            
		        try {
		        	captureThread.stop();
		        		line.stop();
		        		System.out.println("Inizio a salvare il file");
		        		
		        		audioInputStream= new AudioInputStream(line);
		        		File fileOut = new File("java.wav");
		        		fileType = AudioFileFormat.Type.WAVE;
		        		if (AudioSystem.isFileTypeSupported(fileType,audioInputStream)) {
			        	 System.out.println("File tipo supportato, salvando...");

		        		  AudioSystem.write(audioInputStream, fileType, fileOut);
		        		  System.out.println("File salvato");
		        		  ConvertFileToAIFF("java.wav","java.aiff");
		        		  System.out.println("File Convertito");
		        		}else
		        			System.out.println("Tipo file non supportato");
		        		
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				
			}
		}
	
	public void ConvertFileToAIFF(String inputPath, 
			  String outputPath) {
			  AudioFileFormat inFileFormat;
			  File inFile;
			  File outFile;
			  try {
			    inFile = new File(inputPath);
			    outFile = new File(outputPath);     
			  } catch (NullPointerException ex) {
			    System.out.println("Error: one of the ConvertFileToAIFF" +" parameters is null!");
			    return;
			  }
			  try {
			    // query file type
			    inFileFormat = AudioSystem.getAudioFileFormat(inFile);
			    if (inFileFormat.getType() != AudioFileFormat.Type.AIFF) 
			    {
			      // inFile is not AIFF, so let's try to convert it.
			      AudioInputStream inFileAIS = 
			        AudioSystem.getAudioInputStream(inFile);
			      inFileAIS.reset(); // rewind
			      if (AudioSystem.isFileTypeSupported(
			             AudioFileFormat.Type.AIFF, inFileAIS)) {
			         // inFileAIS can be converted to AIFF. 
			         // so write the AudioInputStream to the
			         // output file.
			         AudioSystem.write(inFileAIS,
			           AudioFileFormat.Type.AIFF, outFile);
			         System.out.println("Successfully made AIFF file, "
			           + outFile.getPath() + ", from "
			           + inFileFormat.getType() + " file, " +
			           inFile.getPath() + ".");
			         inFileAIS.close();
			         return; // All done now
			       } else
			         System.out.println("Warning: AIFF conversion of " 
			           + inFile.getPath()
			           + " is not currently supported by AudioSystem.");
			    } else
			      System.out.println("Input file " + inFile.getPath() +
			          " is AIFF." + " Conversion is unnecessary.");
			  } catch (UnsupportedAudioFileException e) {
			    System.out.println("Error: " + inFile.getPath()
			        + " is not a supported audio file type!");
			    return;
			  } catch (IOException e) {
			    System.out.println("Error: failure attempting to read " 
			      + inFile.getPath() + "!");
			    return;
			  }
			}
	
}
